--
-- Author: dbliu
-- Date: 2014-02-26 17:30:36
--


local EM = class("EM", cc.mvc.ModelBase)

-- 定义事件
EM.CHANGE_STATE_EVENT = "CHANGE_STATE_EVENT"
EM.START_EVENT = "START_EVENT"
EM.KILL_EVENT = "KILL_EVENT"

-- 定义属性
EM.schema = clone(cc.mvc.ModelBase.schema)

function EM:ctor(properties, events, callbacks)

	EM.super.ctor(self,properties)

	--因为角色存在不同状态，所以这里为 Actor 绑定了状态机组建
	self:addComponent("components.behavior.StateMachine")

	-- 由于状态机近提供内部使用，所以不应该调用组建的 exprotMethods() 方法,改为用内部属性保存状态机组建对象
	self.fsm__ = self:getComponent("components.behavior.StateMachine")

	-- 设置状态机的默认事件
	local defaultEvents = {
		-- 初始化后，角色处于 idle 状态
		{name = "start", from = "none", to = "idle"},
		-- 被杀
		{name = "kill",   from = "*", to = "dead"},
	}

	-- 如果继承类提供了其他事件，则合并
	table.insertTo(defaultEvents, totable(events))

	-- 设计状态机的默认回调
	local defaultCallbacks = {
		onstart = handler(self, self.onStart),
		onkill = handler(self, self.onKill),
	}

	-- 如果继承类提供了其他回调，则合并
	table.merge(defaultCallbacks,totable(callbacks))

	self.fsm__:setupState({
		events = defaultEvents,
		callbacks = defaultCallbacks
	})

end

function EM:getFSM()
    return self.fsm__
end

function EM:onStart( event )

    local x = tonum(event.args[1])
    local y = tonum(event.args[2])

	event = {name = EM.START_EVENT, from = event.from, to = event.to ,id=self:getId() , x=x , y=y }
    self:dispatchEvent(event)
end

function EM:onKill(event)
	event = {name = EM.KILL_EVENT, from = event.from, to = event.to ,id=self:getId() }
    self:dispatchEvent(event)
end

return EM